import React, { useMemo, useState } from "react";
import SearchDialog from "../../Component/SearchDialog";
import { Button, Table } from "antd";

interface IEditModulesProps {
    tableColumns: any[];
    searchColumns?: any[];
    tableWidth?: number;
    endPoint: string;
    value?: any[];
    formatRequest?: (data: any) => any;
    formatResponse?: (data: any) => any;
    onChange?: (data: any[]) => void;
    expandColumns?: any[];
    expandSourceName?: string;
    enableExpandChecked?: boolean;
}
const EditModules = (props: IEditModulesProps) => {
    const searchFields: Admin.IAdvancedField[] = props.searchColumns || [];
    const tableColumns: any[] = props.tableColumns ||[];
    const [ open, setOpen ] = useState(false);
    const [ selectedList, setSelectedList ] = useState(props.value || []);

    const selectedTableColumns = useMemo(() => tableColumns.map((item) => {
        return {
            ...item,
            render: (text: any, record: any, opt: any) => {
                return item.render ? item.render(text, record, {
                    ...opt,
                    rowChecked: true,
                    mapData: selectedList.find((item: any) => item.id === record.id),
                    setData: (newData: any) => {
                        const newSelectedList = selectedList.map((item) => item.id === record.id ? {
                            ...item,
                            ...newData
                        } : item);
                        setSelectedList(newSelectedList);
                        typeof props.onChange === "function" && props.onChange(newSelectedList);
                    }
                }) : text;
            }
        };
    }), [tableColumns, selectedList]);

    return (<section>
        <Button type="primary" onClick={() => setOpen(true)}>选择模块</Button>
        <Table
            columns={selectedTableColumns}
            dataSource={selectedList}
            bordered
            scroll={{ x: props.tableWidth || 800 }}
        />
        <SearchDialog
            searchFields={searchFields}
            tableColumns={tableColumns}
            tableWidth={props.tableWidth || 800}
            expandColumns={props.expandColumns}
            expandSourceName={props.expandSourceName}
            enableExpandChecked={props.enableExpandChecked}
            open={open}
            onCancel={() => setOpen(false)}
            onConfirm={(listData: any[]) => {
                setSelectedList(listData);
                setOpen(false);
                typeof props.onChange === "function" && props.onChange(listData);
            }}
            width={800}
            endPoint={{
                endPoint: props.endPoint,
                formatRequest: props.formatRequest,
                formatResponse: props.formatResponse
            }}
            defaultSelectedList={props.value || []}
        />
    </section>);
};

export default EditModules;